#!/usr/bin/python
#
# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""This code creates new companies from a text file"""

__author__ = 'felipel+bulk@google.com (Felipe Lora)'

# Locate the client library. If module was installed via "setup.py" script, then
# the following two lines are not needed.
import os
import sys
sys.path.insert(0, os.path.join('..', '..', '..', '..'))

# Import appropriate classes from the client library.
from adspygoogle.common import Utils
from adspygoogle.dfp.DfpClient import DfpClient
from adspygoogle.dfp import DfpUtils
from adspygoogle.dfp.DfpErrors import *
from copy import deepcopy

# Initialize client object.
client = DfpClient(path=os.path.join('..', '..', '..', '..'))

# Initialize appropriate service. By default, the request is always made against
# the production environment.
custom_targeting_service = client.GetCustomTargetingService('https://www.google.com', 'v201108')

networkCT = []

# Define names of logs
warningLog = "warnings_targeting.log"
errorLog = "errors_targeting.log"
successLog = "success_targeting.log"

#############################################################

# Get all the ad units from the network and add their level
def getNetworkCustomTargeting():
  global networkCT
  off_set = '0'
  values = [{
      'key' : 'offset',
      'value' : {
                  'xsi_type' : 'TextValue',
                  'value' : off_set }
  }]

  filterStatement =  {'query' : 'LIMIT 500 OFFSET ' + off_set,
                      'values': values}

  page = custom_targeting_service.GetCustomTargetingKeysByStatement(filterStatement)

  while True:
    if int(page[0]['totalResultSetSize']) < 500:
      for ct in page[0]['results']:
        networkCT.append(ct)
      break

    for ct in page[0]['results']:
      networkCT.append(ct)

    o = int(off_set) + 500
    off_set = str(o)
    filterStatement =  {'query' : 'LIMIT 500 OFFSET ' + off_set ,
                        'values': values}
    page = custom_targeting_service.GetCustomTargetingKeysByStatement(filterStatement)


 
# Read all the custom targeting to be created from the DoubleClick standard text file
def getFileCustomTargeting(customTargetingFile):
  global networkCT
  getNetworkCustomTargeting()
     
  customTargeting = []
  fcustomTargeting = open(customTargetingFile,'rU')

  name_indexer = dict((n['name'],i) for i,n in enumerate(networkCT))

  for line in fcustomTargeting.readlines():
    validator = 1
    currLine = line.rsplit("^")
    key = {}
    keyName = currLine[0]
    keyDisplayName = currLine[1]
    keyValues = currLine[2].rsplit(',')

    if (len(keyName) < 11) and (keyName not in name_indexer) :
      key['name'] = keyName
    else :
      ferror = open(errorLog,'a')
      if len(keyName) > 10 :
        m = "%s, %s, The length of the key name exceeds 10 characters\n" % (keyName, keyDisplayName)
      else :
        m = "%s, %s, The key already exists in your network\n" % (keyName, keyDisplayName)
      ferror.write(m)
      ferror.close()
      validator = 0
    
    key['type'] = "PREDEFINED"
    key['displayName'] = keyDisplayName
    key['values'] = keyValues
    
    if validator == 1:
      customTargeting.append(key)

  return customTargeting

def createCustomTargeting(customTargeting):
  kTemp = deepcopy(customTargeting)
  for k in kTemp:
    del k['values']

  # Create keys
  try:
    keys_created = custom_targeting_service.CreateCustomTargetingKeys(kTemp)
  except DfpRequestError,e:
    warningLogFile = open(warningLog,'a')
    message = "%s\n"  % (e.fault_string)
    warningLogFile.write(message)
    warningLogFile.close()

  # Create values
  i = 0
  values = []
  for kC in keys_created:
    for v in customTargeting[i]['values']:
      value = { 'customTargetingKeyId' : kC['id'],
                'displayName' : v,
                'name' : v }
      values.append(value)
    i = i + 1
  
  try: 
    values = custom_targeting_service.CreateCustomTargetingValues(values)
    fs = open(successLog,'a')
    j = 0
    for kv in keys_created:
      m = "%s,%s,%s\n" % (kv['id'],kv['name'],kv['displayName'])
      fs.write(m)
      j = j+1
    fs.close()  
  except DfpRequestError,e:
    warningLogFile = open(warningLog,'a')
    message = "%s\n"  % (e.fault_string)
    warningLogFile.write(message)
    warningLogFile.close()

  return 1


def Main():
  # Clean old logs
  f = open(warningLog,'w')
  f.write("Name, Display Name, Message\n")
  f.close()
  f = open(errorLog,'w')
  f.write("Name, Display Name, Message\n")
  f.close()
  f = open(successLog,'w')
  f.write("ID, Name, Display Name\n")
  f.close()

  # Read the ad units from the text file
  args = sys.argv[1:]
  customTargetingFile = args[0]
  customTargeting = getFileCustomTargeting(customTargetingFile)
  # Create the custom targeting key / values
  createCustomTargeting(customTargeting)


if __name__ == '__main__':
  Main()
 

